#include "StdAfx.h"
#include "workthread.h"
#include <process.h>


CWorkThread::CWorkThread(void)
{
	m_hThread = NULL;
	m_bQuit = FALSE;
}

CWorkThread::~CWorkThread(void)
{
	ClearThread();
}


void CWorkThread::StartThread()
{
	DWORD threadID;
//	m_hThread = (HANDLE) _beginthreadex(NULL, 0, BogusThreadfunc, 
//											this, CREATE_SUSPENDED,  &threadID);
	ClearThread();
	m_bQuit = FALSE;
	m_hThread = CreateThread(NULL, 0, 
		(LPTHREAD_START_ROUTINE)BogusThreadfunc, this, CREATE_SUSPENDED , &threadID);

}

void CWorkThread::SuspendWorkThread(void)
{
	if(m_hThread == NULL)
		return ;
	else
		SuspendThread(m_hThread);
}

void CWorkThread::ResumeWorkThread(void)
{
	DWORD dwRT = 0;
	if(m_hThread != NULL)
		dwRT = ResumeThread(m_hThread);
}

void CWorkThread::ExitThread(void)
{
	m_bQuit = TRUE;
}

bool CWorkThread::AttachWindow(HWND hWnd)
{
	if(hWnd != NULL)
	{
		m_hMainWnd = hWnd;
		return TRUE;
	}

	else
		return FALSE;


}

//-----------------------------------------
UINT CWorkThread::ThreadFunction(void)
{
	//here you do all your real work
	AttachWindow(NULL);
	HANDLE handle = NULL;
	while(!m_bQuit)
	{
		WaitForSingleObject(handle, INFINITE);
	}
	ExitThread();
	return 0;
}

DWORD CWorkThread::BogusThreadfunc(LPVOID lpparam)
{
	CWorkThread* This = (CWorkThread*)lpparam;
	return This->ThreadFunction();
}
void CWorkThread::ClearThread(void)
{
	if(m_hThread != NULL)
	{
		CloseHandle(m_hThread);
		m_hThread = NULL;
	}
}
